<template>
  <div style="background-color: white; width: 100%;height: 100%;padding: 20px 10px;">
    
    <van-popup v-model="showFiles" position="left" :style="{ height: '100%' }" >
      <div class="files">
        <div v-for="(item,i) in data" :key="i" @click="selectPaperFile(item.id,item.fileName)">
          {{ item.fileName }}
        </div>
      </div>
    </van-popup>
    <div style="width:100%;margin-bottom:20px;">
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="searchQuery">
          <a-row>
            <a-col :span="24">
              <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="supplier">
                <a-input placeholder="请输入文件名称" style="width: 150px" v-model="queryParam.fileName"/>
                <a-button type="primary" @click="searchQuery" icon="search" style="margin-left: 8px">查询</a-button>
                <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="24" style="margin-bottom: 20px;">
              <a-button @click="showFiles = true" type="primary" style="margin-right: 8px">文件夹</a-button>
              <a-button @click="uploadFile" v-has="'customer:uploadFile'" type="primary" icon="plus" style="margin-right: 8px">上传文件</a-button>
              <a-button @click="openFileTrends" type="primary">文件动态</a-button>
            </a-col>
            <a-col :span="24">
              <a-dropdown v-if="selectedRowKeys.length > 0 && this.currentParentId !== 5" v-has="'customer:batchDelFile'">
                <a-menu slot="overlay">
                  <a-menu-item key="1" @click="batchDel">
                    <a-icon type="delete"/>
                    删除
                  </a-menu-item>
                </a-menu>
                <a-button> 批量操作
                  <a-icon type="down"/>
                </a-button>
              </a-dropdown>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div>
        <!-- <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;" v-if="this.currentParentId !== 5">
          <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{
          selectedRowKeys.length }}</a>项
          <a style="margin-left: 24px" @click="onClearSelected">清空</a>
        </div> -->
        <div class="list">
          <van-list
            v-model="loading"
            :finished="finished"
            offset="10"
            finished-text="没有更多了"
            @load="onLoadList"
            :immediate-check="false">
            <van-collapse v-model="activeName" accordion>
              <van-collapse-item 
              
                :name="i"
                v-for="(item,i) in dataSource"
                :key="i">
                <template #title>
                  <div style="font-size:13px;">{{ item.fileName }}</div>
                </template>
                <div class="list-item">
                  <div>文件名：{{ item.fileName }}</div>
                  <div>上传时间：{{ item.createTime }}</div>
                  <div>修改时间：{{item.updateTime}}</div>
                  <div>上传人：{{item.createBy}}</div>
                  <div>文件类型：{{item.fileType}}</div>
                  <div>是否可见：<a-checkbox :checked="item.isShow === 1" @click="changeIsShow(item, i)"></a-checkbox></div>
                  <div>文件大小/kb：{{item.fileSize}}</div>
                  <div>操作：
                    <span >
                      <a v-has="'customer:reNameFile'" @click="reNameFile(item)">重命名</a>
                      <a-divider v-has="'customer:reNameFile'" type="vertical"/>
                      <a @click="preview(item, 1)" v-if="['pdf','jpg','jpeg','png','bmp','gif','webp','svg','psd','tif','tga'].includes(item.fileType)">预览</a>
                      <a @click="preview(item)" v-else-if="['mp4','avi','flv','rmvb'].includes(item.fileType)">播放</a>
                      <a @click="download(item)" v-else>下载</a>
                      <a-divider type="vertical"/>
                      <a @click="moveFile(item)">转移</a>
                      <a-divider type="vertical" v-if="show(item)"/>
                      <a-popconfirm title="确定删除吗?" v-if="show(item)" @confirm="() => deleteFile(item.id)">
                      <a>删除</a>
                      </a-popconfirm>
                    </span>
                  </div>
                </div>
              
              </van-collapse-item>
            </van-collapse>
          </van-list>
        </div>
      </div>
      <file-trends ref="fileTrends"></file-trends>
      <re-name-modal ref="reNameModal" @ok="modalFormOk(arguments)"></re-name-modal>
      <move-file-modal ref="moveFileModal" @ok="modalFormOk(arguments)"></move-file-modal>
      <upload-file-modal ref="uploadFileModal" @ok="modalFormOk(arguments)"></upload-file-modal>
    </div>
  </div>
</template>

<script>
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { deleteAction, getAction } from '@/api/manage'
  import { filterObj } from '@/utils/util'
  import fileTrends from './modules/fileTrends'
  import reNameModal from './modules/reNameModal'
  import moveFileModal from './modules/moveFileModal'
  import uploadFileModal from './modules/uploadFileModal'
  import { putAction } from '../../../../../api/manage'
  import { ImagePreview } from 'vant';
  export default {
    name: 'GhCustomerFileInfoList',
    mixins: [JeecgListMixin, mixinDevice],
    components: {
      fileTrends,
      reNameModal,
      moveFileModal,
      uploadFileModal
    },
    props: {
      customerId: {
        required: true,
        default: 0
      },
    },
    data() {
      return {
        showFiles:false,
        activeName:'',
        finished: false,
        activeKey: [1],
        id: '',
        listLoading: false,
        busy: false,
        description: '客户文件信息表管理页面',
        data: [],
        dataSource: [],
        queryParam: {},
        ipagination: {},
        loading: false,
        selectedRowKeys: [],
        selectionRows: [],
        currentParentId: 1,   //默认打开第一个文件夹的内容
        currentParentName:'现场勘测',
        columns: [
          {
            title: '文件名',
            align: 'center',
            dataIndex: 'fileName',
          },
          {
            title: '上传时间',
            align: 'center',
            dataIndex: 'createTime'
          },
          {
            title: '修改时间',
            align: 'center',
            dataIndex: 'updateTime'
          },
          {
            title: '上传人',
            align: 'center',
            dataIndex: 'createBy'
          },
          {
            title: '文件类型',
            align: 'center',
            dataIndex: 'fileType'
          },
          {
            title: '是否可见',
            align: 'center',
            dataIndex: 'isShow',
            slots: { title: 'customTitle' },
            scopedSlots: { customRender: 'isShow' },
          },
          {
            title: '文件大小/kb',
            align: 'center',
            dataIndex: 'fileSize',
          },
          {
            title: '操作',
            dataIndex: 'action',
            scopedSlots: { customRender: 'action' },
            align: 'center',
            width: 200
          }
        ],
        isorter: {
          column: 'createTime',
          order: 'desc'
        },
        superQueryParams: '',
        superQueryMatchType: 'and',
        url: {
          list: '/ghCustomerFileInfo/list',
          queryList: '/ghCustomerFileInfo/queryList',
          delete: '/ghCustomerFileInfo/delete',
          exportXlsUrl: '/ghCustomerFileInfo/exportXls',
          importExcelUrl: '/ghCustomerFileInfo/importExcel',
          deleteBatch: '/ghCustomerFileInfo/deleteBatch',
          fileTrendsList: '/ghCustomerFileTrendsRecord/list',
          edit: "/ghCustomerFileInfo/edit",
        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        dictOptions: {},
        superFieldList: [],
        fileTrendsData: [],
      }
    },
    computed: {
      importExcelUrl: function () {
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
      },
    },
    created() {
      this.ipagination.current = 1
      this.fetchData()
      this.loadTableData(this.currentParentId)
    },
    methods: {
      onLoadList(){
        this.ipagination.current++
        this.loadTableData(this.currentParentId)
        //, this.ipagination.current
      },
      preview(record,i){
        if(i){
          ImagePreview([record.fileUrl]);
        }else{
          window.open(record.fileUrl)
        }
        
      },
      download(record) {
        window.location = record.fileUrl
        /*window.location = record.fileUrl + '?response-content-type=application/octet-stream'*/
      },
      deleteFile(id) {
        if (!this.url.delete) {
          this.$message.error('请设置url.delete属性!')
          return
        }
        deleteAction(this.url.delete, {
          id: id
        }).then((res) => {
          if (res.success) {
            this.reCalculatePage(1)
            this.loadTableData(this.currentParentId)
            this.$message.success(res.message)
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      changeIsShow(item, i){
        let params = {};
        params.id = item.id;
        if (item.isShow === 1){
          params.isShow = 2;
        }else if (item.isShow === 2){
          params.isShow = 1;
        }
        putAction(this.url.edit,params).then((res)=> {
          if (res.success) {
            this.$message.success(res.message);
            this.dataSource[i].isShow = item.isShow===1?2:1
            // this.loadTableData(this.currentParentId)
          } else {
            this.$message.warning(res.message);
          }
        })
      },
      uploadFile() {
        if (this.currentParentId == 12 && this.dataSource.length >= 1){
          this.$message.warning("封面图只能上传一张照片")
          return;
        }
        //传递客户id和目录id
        this.$refs.uploadFileModal.add(this.customerId, this.currentParentId, this.currentParentName)
        this.$refs.uploadFileModal.title = '上传文件'
        this.$refs.uploadFileModal.disableSubmit = false
      },
      reNameFile(record) {
        this.$refs.reNameModal.edit(record)
        this.$refs.reNameModal.title = '重命名'
        this.$refs.reNameModal.disableSubmit = false
      },
      moveFile(record) {
        this.$refs.moveFileModal.edit(record)
        this.$refs.moveFileModal.title = '转移文件目录'
        this.$refs.moveFileModal.disableSubmit = false
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectionRows = selectionRows
      },
      onClearSelected() {
        this.selectedRowKeys = []
        this.selectionRows = []
      },
      fetchData() {
        getAction(this.url.queryList).then((res) => {
          if (res.success) {
            this.data = res.result
          }
        })
      },
      selectPaperFile(id,name) {
        this.ipagination.current = 1
        this.dataSource = []
        this.currentParentId = id;
        this.currentParentName = name;
        this.loadTableData(id)
      },
      searchQuery() {
        this.ipagination.current = 1
        this.dataSource = []
        this.loadTableData(this.currentParentId)
      },
      searchReset() {
        this.ipagination.current = 1
        this.dataSource = []
        this.queryParam = {}
        this.loadTableData(this.currentParentId)
      },
      modalFormOk(msg) {
        this.ipagination.current = 1
        this.dataSource = []
        this.loadTableData(this.currentParentId)
      },
      loadTableData(parentId) {
        if (this.ipagination.current == 1) {
          this.dataSource = []
          this.finished = false;
        }
        let params = this.getQueryParams()
        params.customerId = this.customerId
        params.parentId = this.currentParentId
        

        this.loading = true
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            this.loading = false
            this.dataSource = [...this.dataSource, ...res.result.records];
            if(res.result.total){
              this.ipagination.total = res.result.total;
            } else {
              this.ipagination.total = 0;
            }
          }
          this.loading = false
          if(res.result.records.length<10){
            this.finished = true;
          }
        })
      },
      handleTableChange(pagination, filters, sorter) {
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field
          this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
        }
        this.ipagination = pagination
        this.loadTableData(this.id)
      },
      getQueryParams() {
        let sqp = {}
        if (this.superQueryParams) {
          sqp['superQueryParams'] = encodeURI(this.superQueryParams)
          sqp['superQueryMatchType'] = this.superQueryMatchType
        }
        let param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
        param.field = this.getQueryField()
        param.pageNo = this.ipagination.current
        param.pageSize = this.ipagination.pageSize
        return filterObj(param)
      },
      getQueryField() {
        let str = 'id,'
        this.columns.forEach(function (value) {
          str += ',' + value.dataIndex
        })
        return str
      },
      batchDel: function () {
        let that = this;
        if (!this.url.deleteBatch) {
          this.$message.error('请设置url.deleteBatch属性!')
          return
        }
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning('请选择一条记录！')
          return
        } else {
          let ids = ''
          for (let a = 0; a < this.selectedRowKeys.length; a++) {
            ids += this.selectedRowKeys[a] + ','
          }
          this.$confirm({
            title: '确认删除',
            content: '是否删除选中数据?',
            onOk: function () {
              deleteAction(that.url.deleteBatch, { ids: ids }).then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.loadTableData(that.currentParentId)
                } else {
                  that.$message.warning(res.message)
                }
              })
            }
          })
        }
      },
      openFileTrends() {
        getAction(this.url.fileTrendsList, {
          customerId: this.customerId
        }).then((res) => {
          if (res.success) {
            this.fileTrendsData = res.result.records || res.result
            this.$refs.fileTrends.showFileTrendsDrawer(this.fileTrendsData)
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      show(record) {
        if(record.parentName === '封面图') {
          return false;
        } else if(record.parentName === '合同协议' && !record.deleteFlag) {
          return false;
        }
        return true;
      }
    }
  }
</script>

<style scoped lang="less">
  @import '~@assets/less/common.less';
  .files{
    width: 50vw;
    overflow-y: scroll;
    height: 100%;
    div{
      height: 50px;
      text-align: center;
      line-height: 50px;
      border-bottom: 1px solid #e8e8e8;
    }
  }
  .list /deep/ .van-cell{
    height: 50px;
    align-items: center;
    border: 1px solid #fff !important;
  }
  .list /deep/ .van-cell__title{
    overflow:hidden;
    white-space:nowrap;
    text-overflow:ellipsis;
  }
  .list{
    overflow-y: scroll;
    height:60vh;
  }
  .list-item{
    line-height: 40px;
    border-top: 1px solid #f6f6f6;
    font-size: 12px;
  }
  ::-webkit-scrollbar {
    display: none;
  }
  .selectd {
    color: red;
  }

  .infinite-container {
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    overflow: auto;
    padding: 8px 24px;
    height: 400px;
  }

  .loading-container {
    position: absolute;
    bottom: 40px;
    width: 100%;
    text-align: center;
  }
</style>